// API configuration and base service
import { createSecurePayload, extractSecurePayload, encryptData, decryptData } from '../utils/encryption';

const API_BASE_URL = process.env.REACT_APP_API_URL || 'http://localhost:3001/api';

class ApiService {
  constructor(baseUrl = API_BASE_URL) {
    this.baseUrl = baseUrl;
  }

  // Generic request method
  async request(endpoint, options = {}, encryptPayload = false) {
    const url = `${this.baseUrl}${endpoint}`;
    
    // Prepare request body
    let body = options.body;
    if (body && encryptPayload) {
      // Encrypt the request body if encryption is requested
      body = JSON.stringify(createSecurePayload(JSON.parse(body)));
    }
    
    const config = {
      headers: {
        'Content-Type': 'application/json',
        'X-Encrypted': encryptPayload ? 'true' : 'false',
        ...options.headers,
      },
      ...options,
    };

    // Add the encrypted body to the config
    if (body) {
      config.body = body;
    }

    // Add authorization token if available
    const token = localStorage.getItem('authToken');
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }

    try {
      const response = await fetch(url, config);
      
      // Handle HTTP errors
      if (!response.ok) {
        let errorMessage = `HTTP error! status: ${response.status}`;
        try {
          const errorData = await response.json();
          // Check if the error response is encrypted
          if (response.headers.get('X-Encrypted') === 'true') {
            const decryptedError = extractSecurePayload(errorData);
            errorMessage = decryptedError.message || errorMessage;
          } else {
            errorMessage = errorData.message || errorMessage;
          }
        } catch (e) {
          // If error parsing fails, use the default error message
        }
        throw new Error(errorMessage);
      }

      // Parse the response
      const responseData = await response.json();
      
      // Check if the response is encrypted
      if (response.headers.get('X-Encrypted') === 'true') {
        return extractSecurePayload(responseData);
      }
      
      return responseData;
    } catch (error) {
      console.error('API request failed:', error);
      throw error;
    }
  }

  // GET request
  async get(endpoint, params = {}) {
    const queryString = new URLSearchParams(params).toString();
    const url = queryString ? `${endpoint}?${queryString}` : endpoint;
    return this.request(url, { method: 'GET' });
  }

  // POST request
  async post(endpoint, data = {}, encrypt = false) {
    return this.request(endpoint, {
      method: 'POST',
      body: JSON.stringify(data),
    }, encrypt);
  }

  // PUT request
  async put(endpoint, data = {}, encrypt = false) {
    return this.request(endpoint, {
      method: 'PUT',
      body: JSON.stringify(data),
    }, encrypt);
  }

  // DELETE request
  async delete(endpoint) {
    return this.request(endpoint, { method: 'DELETE' });
  }
}

export default new ApiService();